﻿/***************************
* 1.特产列表
* 2.特产详情
****************************/

/* 变量 */
var localproduct = "elements/localproduct.html";
var localproductDetail = "elements/localproductDetail.html";

/* 特产 */
var contactsCallback_localproduct = myApp.onPageInit('localproduct', function (page) {

    // 过滤 全部美食显示
    $$(".navbar-inner .right img").hide();
    $$(".navbar-inner .right img").hide();

    // JSON
    var lo_conditionParams = JSON.stringify({
        type: 7,
        Identifier: "mobile/wanzhuan/mai"
    });

    $$.ajax({
        url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.CMS,
        crossDomain: true,
        data: { "content": lo_conditionParams },
        method: "POST",
        success: function (data, status) {
            data = JSON.parse(data);
            if (data && data.status == "0" && data.results.length > 0) {
                for (var i = 0; i < data.results.length; i++) {
                    // 格式化数据
                    for (var j = 0; j < data.results[i].value.length; j++) {
                        if (data.results[i].value[j].F_SmallImage == undefined || data.results[i].value[j].F_SmallImage == null || data.results[i].value[j].F_SmallImage == "") {
                            data.results[i].value[j].F_SmallImage = NoPicture();
                        };
                    }

                    if (data.results[i].name == "tuijiantechan") {
                        var searchTemplate = $$('#template-localproduct-tab1').html();
                        if (searchTemplate) {
                            var compiledTemplate = Template7.compile(searchTemplate);
                            var html = compiledTemplate(data.results[i]);
                            $$("#localproduct_tab1 .content-block").append(html);
                            flag_InfiniteScroll = flag_needScroll = true;
                        }
                    }
                }
            }
        },
        error: function (xhr, status) { }
    });

    //点击第一次页面执行
    var flag_localproduct_tab2 = true;
    //删除滚动后重新添加滚动
    var flag_InfiniteScroll = true;
    //是否需要滚动加载
    var flag_needScroll = true;
    //滚动事件只执行一次
    var flag_execute = false;

    var index_tab1 = 1;
    var index_tab2 = 1;
    var index_tab3 = 1;
    var current_tabindex = 0;
    var size = 10;
    // 加载flag
                        var loading = false;

    //全部特产
    $$("#buttons-tabs a").click(function () {
        $$('.infinite-scroll').scrollTop(0);
        $$(".navbar-inner .right img").hide();

        if ($$(this).index() == 1 && flag_localproduct_tab2) {
            LoadLocalProductAll(index_tab1, size);
            flag_localproduct_tab2 = false;
        }
    });

    //加载数据
    function LoadLocalProductAll(pageindex, pagesize) {
        var v_district = "";    //区域
        var v_localproductType = "";  //特产类型
        var v_likeCountOrder = "";  //热度

        var order = [];
        if (current_tabindex == 0) {
            order = [
                {
                    OrderField: "TopPX", //综合排序
                    OrderType: "desc"
                },
                {
                    OrderField: "Sort",
                    OrderType: "desc"
                }
            ]
        }
        else if (current_tabindex == 1) {
            order = [
                {
                    OrderField: "likeCount", 
                    OrderType: "desc"
                }
            ]
        }
        else if (current_tabindex == 2) {
            order = [
                {
                    OrderField: "SaleNum", //销量排序
                    OrderType: "desc"
                }
            ]
        };

        var _content = JSON.stringify({
            "type": 0,
            "conditionParams": {
                "Page": {
                    "PageSize": pagesize,
                    "PageIndex": pageindex
                },
                "Search": [],
                "Order": order
            }
        });
        myApp.showPreloader();
        $$.ajax({
            url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.LOCALPRODUCT,
            data: 'content=' + _content,
            crossDomain: true,
            dataType: "jsonp",
            success: function (data, status) {
                myApp.hidePreloader();
                data = JSON.parse(data);
                loading=false;

                if (current_tabindex == 0 && index_tab1 == 1) {
                    $$("#localproduct_tab2 #sub_tab1 .content-block ul").children("li").remove();
                }
                if (current_tabindex == 1 && index_tab1 == 2) {
                    $$("#localproduct_tab2 #sub_tab2 .content-block ul").children("li").remove();
                }
                if (current_tabindex == 2 && index_tab1 == 3){
                    $$("#localproduct_tab2 #sub_tab3 .content-block ul").children("li").remove();
                }


                if (data.status == "0" && data.results.length > 0) {
                    // 格式化数据
                    for (var i = 0; i < data.results.length; i++) {
                        if (data.results[i].getImage && data.results[i].getImage.smallImageFrontUrl && (
                            data.results[i].getImage.smallImageFrontUrl == null || data.results[i].getImage.smallImageFrontUrl == "")) {
                            data.results[i].getImage.smallImageFrontUrl = NoPicture();
                        };
                        data.results[i].distance = ISS.utils.toFixed(data.results[i].distance, 2);
                    }

                    var searchTemplate = $$('#template-localproduct-tab2').html();
                    if (searchTemplate) {
                        var compiledTemplate = Template7.compile(searchTemplate);
                        var html = compiledTemplate(data);
                        if (current_tabindex == 0) $$("#localproduct_tab2 #sub_tab1 .content-block ul").append(html);
                        else if (current_tabindex == 1) $$("#localproduct_tab2 #sub_tab2 .content-block ul").append(html);
                        else if (current_tabindex == 2) $$("#localproduct_tab2 #sub_tab3 .content-block ul").append(html);
                        flag_InfiniteScroll = flag_needScroll = true;
                    }

                    //tab1综合,无限滚动只加载一次
                    if (!flag_execute) {
                        //只执行一次
                        flag_execute = true;

                        
                        $$('.infinite-scroll').on('infinite', function () {
                            //综合 价格 距离 切换
                            if (!flag_needScroll) {
                                flag_needScroll = true;
                                return;
                            }

                            //查询时,删除滚动后重新绑定pageindex
                            if (!flag_InfiniteScroll) {
                                flag_InfiniteScroll = true;
                                return;
                            }

                            if ($$("#a_localproduct_tab2").hasClass("active")) {
                                // 如果正在加载，则退出
                                if (loading) return;
                                // 设置flag
                                loading = true;
                                // 模拟1s的加载过程
                                setTimeout(function () {
                                    
                                    if (current_tabindex == 0) {
                                        index_tab1++;
                                        LoadLocalProductAll(index_tab1, pagesize);
                                    }
                                    else if (current_tabindex == 1) {
                                        index_tab2++;
                                        LoadLocalProductAll(index_tab2, pagesize);
                                    }
                                    else if (current_tabindex == 2) {
                                        index_tab3++;
                                        LoadLocalProductAll(index_tab3, pagesize);
                                    }
                                }, 100);
                            }
                        });
                    }
                    if (current_tabindex == 0 && $$("#localproduct_tab2 #sub_tab1 .content-block ul li").length >= data.total) {
                        // 删除加载提示符
                        $$('.infinite-scroll-preloader1').remove();
                        // 加载完毕，则注销无限加载事件，以防不必要的加载
                        myApp.detachInfiniteScroll($$('.infinite-scroll'));
                    }
                    else if (current_tabindex == 1 && $$("#localproduct_tab2 #sub_tab2 .content-block ul li").length >= data.total) {
                        // 删除加载提示符
                        $$('.infinite-scroll-preloader2').remove();
                        // 加载完毕，则注销无限加载事件，以防不必要的加载
                        myApp.detachInfiniteScroll($$('.infinite-scroll'));
                    }
                    else if (current_tabindex == 2 && $$("#localproduct_tab2 #sub_tab3 .content-block ul li").length >= data.total) {
                        // 删除加载提示符
                        $$('.infinite-scroll-preloader3').remove();
                        // 加载完毕，则注销无限加载事件，以防不必要的加载
                        myApp.detachInfiniteScroll($$('.infinite-scroll'));
                    }
                }
                else {
                    // 删除加载提示符
                    myApp.detachInfiniteScroll($$('.infinite-scroll'));
                    if (current_tabindex == 0) {
                        $$('.infinite-scroll-preloader1').remove();
                        // 删除多余的提示
                        $$("#localproduct_tab2 #sub_tab1 .content-block .noAnswer").remove();
                        if (data.total == 0) {
                            $$("#localproduct_tab2 #sub_tab1 .content-block").append("<div id='noAnswer' style='margin:auto;text-align:center'>对不起，您搜索的结果不存在！</div>");
                        }
                        //index_tab1--;
                    }
                    else if (current_tabindex == 1) {
                        $$('.infinite-scroll-preloader2').remove();
                        // 删除多余的提示
                        $$("#localproduct_tab2 #sub_tab2 .content-block .noAnswer").remove();
                        if (data.total == 0) {
                            $$("#localproduct_tab2 #sub_tab2 .content-block").append("<div id='noAnswer' style='margin:auto;text-align:center'>对不起，您搜索的结果不存在！</div>");
                        }
                        //index_tab2--;
                    }
                    else if (current_tabindex == 2) {
                        $$('.infinite-scroll-preloader3').remove();
                        // 删除多余的提示
                        $$("#localproduct_tab2 #sub_tab3 .content-block .noAnswer").remove();
                        if (data.total == 0) {
                            $$("#localproduct_tab2 #sub_tab3 .content-block").append("<div id='noAnswer' style='margin:auto;text-align:center'>对不起，您搜索的结果不存在！</div>");
                        }
                        //index_tab2--;
                    }
                }
            },
            error: function (xhr, status) {
                myApp.hidePreloader();
                myApp.alert("服务器连接失败！");
                loading=false;
            }
        });
    }

    //查询条件
    $$(".view-right .right a.close-panel").on("click", function () {
        myApp.attachInfiniteScroll($$('.infinite-scroll'));
        $$("#localproduct_tab2 #sub_tab1 .content-block ul").children("li").remove();
        $$("#localproduct_tab2 #sub_tab2 .content-block ul").children("li").remove();
        $$("#localproduct_tab2 #sub_tab3 .content-block ul").children("li").remove();
        $$(".noAnswer").remove();
        

        flag_InfiniteScroll = false;
        flag_needScroll = true;
        index_tab1 = index_tab2 = index_tab3 = 1;
        if (current_tabindex == 0)
            LoadLocalProductAll(index_tab1, size);
        else if (current_tabindex == 1)
            LoadLocalProductAll(index_tab2, size);
        else if (current_tabindex == 2)
            LoadLocalProductAll(index_tab3, size);
    });

    //综合 价格 距离切换
    $$(".subnavbar").on("click", "a", function () {
        $$('.infinite-scroll').scrollTop(0);
        current_tabindex = $$(this).index();
        myApp.attachInfiniteScroll($$('.infinite-scroll'));
        $$(".noAnswer").remove();

        flag_InfiniteScroll = true;
        flag_needScroll = false;
        if ($$(this).index() == 0 && $$("#localproduct_tab2 #sub_tab1 .content-block ul").children("li").length == 0) {
            LoadLocalProductAll(index_tab1, size);
        }
        if ($$(this).index() == 1 && $$("#localproduct_tab2 #sub_tab2 .content-block ul").children("li").length == 0) {
            LoadLocalProductAll(index_tab2, size);
        }
        if ($$(this).index() == 2 && $$("#localproduct_tab2 #sub_tab3 .content-block ul").children("li").length == 0) {
            LoadLocalProductAll(index_tab3, size);
        }
    });
});

/* 特产详情  */
var contactsCallback_localproductDetail = myApp.onPageInit('localproductDetail', function (page) {
    //获取页面参数
    var scode = ISS.utils.getParameter("scode");
    if (page != undefined) {
        scode = page.query.scode;
    }
    var _content = JSON.stringify({
        type: 1,
        Code: scode
    })
    $$.ajax({
        url: ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.LOCALPRODUCT,
        data: { "content": _content },
        crossDomain: true,
        method: "POST",
        dataType: "jsonp",
        success: function (data, status) {
            data = JSON.parse(data);
            if (data && data.status == "0") {
                var searchTemplate = $$('#template-localproduct-detail').html();
                var compiledSearchTemplate = Template7.compile(searchTemplate);
                var html = compiledSearchTemplate(data.results);
                $$("#localproduct_detail_page .page-content").html(html);

                if (data.results.getImage.imageList.length > 0) {
                    var slidesperview = 3;
                        if (data.results.getImage.imageList.length == 1) {
                            slidesperview = 1;
                        } else if (data.results.getImage.imageList.length == 2) {
                            slidesperview = 2;
                        }

                        var mySwiper = new Swiper('.swiper-localproductDetail', {
                            pagination: '.swiper-localproductDetail .swiper-pagination',
                            autoplay: 5000,
                            speed: 300,
                            spaceBetween: 5,
                            slidesPerView: slidesperview
                        });

                        var ImageList = [];
                        var middleImageList = [];
                        for (var i = 0; i < data.results.getImage.imageList.length; i++) {
                            ImageList[i] = data.results.getImage.imageList[i].smallImgSrc;
                            middleImageList[i] = data.results.getImage.imageList[i].middleImgSrc;
                        }
                        $$("#localproduct_detail_page #swiper").attr("yuqing_ImgList", JSON.stringify(ImageList));
                        $$("#localproduct_detail_page #swiper").attr("yuqing_middleImageList", JSON.stringify(middleImageList));

                        $$("#localproduct_detail_page #swiper").on("click", function () {
                            event.stopPropagation();
                            iss_localStorage.set("yuqing_ImgList", JSON.parse($$(this).attr("yuqing_ImgList")));
                            iss_localStorage.set("yuqing_middleImageList", JSON.parse($$(this).attr("yuqing_middleImageList")));
                            mainView.router.load({ url: "../../view/common/showImageList.html" });
                        })
                }

            }
        },
        error: function (xhr, status) {
            console.log("ajax error!");
        }
    });

    $$("#localproduct_detail_page .page-content").on("click", "div.swiper-container", function () {
        mainView.router.loadPage({ url: $$(this).attr("data-href"), reload: false });
        // window.location.href=$$(this).attr("data-href");
    })
});

/* 初始化  */
function initData() {
    var href = window.location.href;
    if (href.indexOf(localproduct) > -1) {
        contactsCallback_localproduct.trigger();
    }
    else if (href.indexOf(localproductDetail) > -1) {
        contactsCallback_localproductDetail.trigger();
    }
}

initData();

